package com.medical.medicalmodulecommon.minio;

import com.medical.medicalmodulecommon.api.FileService;
import com.medical.medicalmodulecommon.response.CommonResponse;
import com.medical.medicalmodulecommon.response.ResponseCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/api/minio-test")
public class MinioTestController {

    @Autowired
    private FileService fileService;

    /**
     * 测试上传文本文件
     */
    @PostMapping("/upload-text")
    public CommonResponse<Map<String, String>> testUploadText(@RequestParam String content) {
        try {
            String objectName = "test-files/text-" + System.currentTimeMillis() + ".txt";
            byte[] contentBytes = content.getBytes(StandardCharsets.UTF_8);

            String fileUrl = fileService.uploadFile(
                    new ByteArrayInputStream(contentBytes),
                    objectName,
                    "text/plain",
                    contentBytes.length
            );

            Map<String, String> result = new HashMap<>();
            result.put("fileUrl", fileUrl);
            result.put("objectName", objectName);
            result.put("message", "文件上传成功");

            return CommonResponse.createForSuccess(result);
        } catch (Exception e) {
            log.error("文件上传失败", e);
            return CommonResponse.createForError("文件上传失败: " + e.getMessage());
        }
    }
    @PostMapping("/upload-multipart")
    public CommonResponse<Map<String, Object>> testUploadMultipart(
            @RequestParam("file") MultipartFile file,
            @RequestParam(required = false) String objectName) {
        try {
            // 如果未指定对象名称，使用带时间戳的文件名
            if (objectName == null || objectName.trim().isEmpty()) {
                String originalFileName = file.getOriginalFilename();
                String timestamp = String.valueOf(System.currentTimeMillis());
                objectName = "uploads/" + timestamp + "_" + originalFileName;
            }

            String fileUrl = fileService.uploadFile(file, objectName);

            Map<String, Object> result = new HashMap<>();
            result.put("fileUrl", fileUrl);
            result.put("objectName", objectName);
            result.put("originalFileName", file.getOriginalFilename());
            result.put("fileSize", file.getSize());
            result.put("contentType", file.getContentType());
            result.put("message", "文件上传成功");

            return CommonResponse.createForSuccess(result);
        } catch (Exception e) {
            log.error("文件上传失败", e);
            return CommonResponse.createForError("文件上传失败: " + e.getMessage());
        }
    }
    @PostMapping("/upload-simple")
    public CommonResponse<Map<String, Object>> testUploadSimple(@RequestParam("file") MultipartFile file) {
        try {
            String fileUrl = fileService.uploadFile(file);

            Map<String, Object> result = new HashMap<>();
            result.put("fileUrl", fileUrl);
            result.put("objectName", file.getOriginalFilename());
            result.put("fileSize", file.getSize());
            result.put("contentType", file.getContentType());
            result.put("message", "文件上传成功");

            return CommonResponse.createForSuccess(result);
        } catch (Exception e) {
            log.error("文件上传失败", e);
            return CommonResponse.createForError("文件上传失败: " + e.getMessage());
        }
    }
    /**
     * 测试文件是否存在
     */
    @GetMapping("/check-file")
    public CommonResponse<Map<String, Object>> checkFile(@RequestParam String objectName) {
        try {
            boolean exists = fileService.objectExist(objectName);

            Map<String, Object> result = new HashMap<>();
            result.put("objectName", objectName);
            result.put("exists", exists);
            result.put("message", exists ? "文件存在" : "文件不存在");

            return CommonResponse.createForSuccess(result);
        } catch (Exception e) {
            log.error("检查文件失败", e);
            return CommonResponse.createForError("检查文件失败: " + e.getMessage());
        }
    }

    /**
     * 测试删除文件
     */
    @DeleteMapping("/delete-file")
    public CommonResponse<Map<String, Object>> deleteFile(@RequestParam String objectName) {
        try {
            boolean success = fileService.removeObject(objectName);

            Map<String, Object> result = new HashMap<>();
            result.put("objectName", objectName);
            result.put("deleted", success);
            result.put("message", success ? "文件删除成功" : "文件删除失败");

            return CommonResponse.createForCondition(success, result, "文件删除失败");
        } catch (Exception e) {
            log.error("删除文件失败", e);
            return CommonResponse.createForError("删除文件失败: " + e.getMessage());
        }
    }

    /**
     * 测试获取文件URL
     */
    @GetMapping("/get-file-url")
    public CommonResponse<Map<String, String>> getFileUrl(@RequestParam String objectName) {
        try {
            String fileUrl = fileService.getFileUrl(objectName);

            Map<String, String> result = new HashMap<>();
            result.put("objectName", objectName);
            result.put("fileUrl", fileUrl);
            result.put("message", "获取文件URL成功");

            return CommonResponse.createForSuccess(result);
        } catch (Exception e) {
            log.error("获取文件URL失败", e);
            return CommonResponse.createForError("获取文件URL失败: " + e.getMessage());
        }
    }

    /**
     * 综合测试：上传 -> 检查 -> 获取URL -> 删除
     */
    @PostMapping("/comprehensive-test")
    public CommonResponse<Map<String, Object>> comprehensiveTest() {
        try {
            String objectName = "test-files/comprehensive-" + System.currentTimeMillis() + ".txt";
            String content = "这是一个MinIO功能测试文件，时间戳: " + System.currentTimeMillis();
            byte[] contentBytes = content.getBytes(StandardCharsets.UTF_8);

            Map<String, Object> testResults = new HashMap<>();
            testResults.put("objectName", objectName);

            // 1. 上传文件
            log.info("步骤1: 上传文件");
            String fileUrl = fileService.uploadFile(
                    new ByteArrayInputStream(contentBytes),
                    objectName,
                    "text/plain",
                    contentBytes.length
            );
            testResults.put("uploadSuccess", fileUrl != null);
            testResults.put("fileUrl", fileUrl);

            // 2. 检查文件是否存在
            log.info("步骤2: 检查文件是否存在");
            boolean exists = fileService.objectExist(objectName);
            testResults.put("fileExists", exists);

            // 3. 获取文件URL
            log.info("步骤3: 获取文件URL");
            String newFileUrl = fileService.getFileUrl(objectName);
            testResults.put("retrievedFileUrl", newFileUrl);

            // 4. 删除文件
            log.info("步骤4: 删除文件");
            boolean deleted = fileService.removeObject(objectName);
            testResults.put("deleted", deleted);

            testResults.put("message", "综合测试完成");
            testResults.put("allTestsPassed", fileUrl != null && exists && newFileUrl != null && deleted);

            return CommonResponse.createForSuccess("MinIO功能测试完成", testResults);

        } catch (Exception e) {
            log.error("综合测试失败", e);
            return CommonResponse.createForError("综合测试失败: " + e.getMessage());
        }
    }

    /**
     * 测试权限不足场景
     */
    @GetMapping("/test-limits")
    public CommonResponse<String> testLimits() {
        // 模拟权限检查失败场景
        return CommonResponse.createForLimits("您没有权限访问此功能");
    }

    /**
     * 使用快速创建方法测试
     */
    @GetMapping("/test-quick-methods")
    public CommonResponse<Map<String, String>> testQuickMethods() {
        try {
            Map<String, String> data = new HashMap<>();
            data.put("method", "of方法测试");
            data.put("timestamp", String.valueOf(System.currentTimeMillis()));

            // 使用快速创建方法
            return CommonResponse.of(ResponseCode.SUCCESS, data);
        } catch (Exception e) {
            // 使用快速创建错误方法
            return CommonResponse.of(ResponseCode.ERROR, "快速方法测试失败");
        }
    }


}